package com.dindang.ddm.mvp.presenter;

import android.app.Application;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.dindang.checkline.mvp.greendao.controller.CheckItemDetailController;
import com.dindang.checkline.mvp.model.api.Api;
import com.dindang.checkline.mvp.model.entity.BaseResponse;
import com.dindang.checkline.mvp.model.entity.CheckLineEntity;
import com.dindang.checkline.mvp.model.entity.ItemDetailEntity;
import com.dindang.checkline.mvp.model.entity.LineEvent;
import com.dindang.checkline.mvp.model.entity.TaskEvent;
import com.dindang.ddm.app.utils.NetworkConnectChangedReceiver;
import com.dindang.ddm.R;
import com.dindang.ddm.app.AppConst;
import com.dindang.ddm.mvp.contract.MainContract;
import com.dindang.ddm.mvp.model.entity.MainEvent;
import com.dindang.ddm.mvp.model.entity.TabEntity;
import com.dindang.ddm.mvp.ui.adapter.pager.MainPagerAdapter;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.RxLifecycleUtils;
import com.longxi.gamer_base.BaseAppConst;
import com.longxi.gamer_base.MyApplication;
import com.longxi.gamer_base.model.User;
import com.longxi.gamer_base.utils.DateTimeUtils;
import com.longxi.gamer_base.utils.SharedPreferencesUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


@ActivityScope
public class MainPresenter extends BasePresenter<MainContract.Model, MainContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private String[] mTitles = {"消息", "待办", "工作台", "我的"};
    private int[] mIconUnselectIds = {R.mipmap.ic_tab_message_normal, R.mipmap.ic_tab_backlog_normal, R.mipmap.ic_tab_workbench_normal, R.mipmap.ic_tab_me_normal};
    private int[] mIconSelectIds = {R.mipmap.ic_tab_message_select, R.mipmap.ic_tab_backlog_select, R.mipmap.ic_tab_workbench_select, R.mipmap.ic_tab_me_press};

    private MainPagerAdapter mMainPagerAdapter;

    private int mPosition = 1;// 选择第一个页面
    private NetworkConnectChangedReceiver receiver;
    private MainEvent mainEvent = new MainEvent();
    String START_CHECKTIAM = "START_CHECKTIAM";
    @Inject
    public MainPresenter(MainContract.Model model, MainContract.View rootView) {
        super(model, rootView);
    }

    public void initView() {
        EventBus.getDefault().register(this);
        initViewPager();
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void MaintainDetailsRefresh(MainEvent mainEvent) {
        update();//上传缓存的数据
    }

    private void update() {
        if(!SharedPreferencesUtils.getParam(mRootView.getActivity(), START_CHECKTIAM+ BaseAppConst.accountInfo.getUserId(),"").equals("")){
            submitStart();
        }else {
            postData();
        }
    }

    private void submitStart() {
        //点击开始巡检
        CheckLineEntity.ChangeStatus paramStatus = new CheckLineEntity.ChangeStatus();
        String[] strs = ((String)SharedPreferencesUtils.getParam(mRootView.getActivity(), START_CHECKTIAM+ BaseAppConst.accountInfo.getUserId(),"")).split(",");
        paramStatus.id = strs[0];
        paramStatus.dExecute = strs[1];
        mModel.submitStart(paramStatus)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(2, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                .doOnSubscribe(disposable -> {

                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<BaseResponse>(mErrorHandler) {
                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                    }

                    @Override
                    public void onNext(BaseResponse response) {
                        if(response.getStatus().equals(BaseAppConst.OUT_TOKEN)){
                            MyApplication.getInstance().gotoLoginActivity();
                        }
                        if(response.isSuccess()){
                            postData();
                        }
                    }
                });
    }

    private void postData() {//点击提交缓存数据
        //以下是真实调接口
        List<ItemDetailEntity> itemDetailEntitys = CheckItemDetailController.selectNotSubmit();
        if (itemDetailEntitys == null || itemDetailEntitys.size() == 0) {
            return;
        }
        for (int i = 0; i < itemDetailEntitys.size(); i++) {
            int finalI = i;
            mModel.submitItemDetail(itemDetailEntitys.get(i))
                    .subscribeOn(Schedulers.io())
                    .retryWhen(new RetryWithDelay(2, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                    .doOnSubscribe(disposable -> {

                    }).subscribeOn(AndroidSchedulers.mainThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doFinally(() -> {
                    })
                    .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                    .subscribe(new ErrorHandleSubscriber<BaseResponse>(mErrorHandler) {
                        @Override
                        public void onNext(BaseResponse response) {
                            if (response.isSuccess()) {
                                CheckItemDetailController.deleteByid(itemDetailEntitys.get(finalI));
                                LineEvent lineEvent = new LineEvent();
                                TaskEvent taskEvent = new TaskEvent();
                                EventBus.getDefault().post(lineEvent);
                                EventBus.getDefault().post(taskEvent);
                            }
                        }

                        @Override
                        public void onError(Throwable t) {
                            super.onError(t);
                        }
                    });
        }
    }

    public void setNet() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        receiver = new NetworkConnectChangedReceiver();
        mApplication.registerReceiver(receiver, filter);
    }

    public void initUser() {
        String userInfo = SharedPreferencesUtils.getParam(mApplication, AppConst.KEY_ACCOUNT_INFO, "").toString();
        if (!TextUtils.isEmpty(userInfo)) {
            BaseAppConst.accountInfo = JSON.parseObject(userInfo, User.AccountInfo.class);
        }
    }

    public void initListener() {
        mRootView.getCommonTabLayout().setTabData(mTabEntities);
        mRootView.getCommonTabLayout().setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                mRootView.getViewpager().setCurrentItem(position, false);
                mPosition = position;
            }

            @Override
            public void onTabReselect(int position) {
            }
        });

        mRootView.getViewpager().addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                mRootView.getCommonTabLayout().setCurrentTab(position);
                mPosition = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        mRootView.getViewpager().setCurrentItem(mPosition);
        mRootView.getCommonTabLayout().setCurrentTab(mPosition);
    }

    private void initViewPager() {
        mMainPagerAdapter = new MainPagerAdapter(mRootView.getActivity().getSupportFragmentManager(), mTitles);
        mRootView.getViewpager().setAdapter(mMainPagerAdapter);
        mRootView.getViewpager().setOffscreenPageLimit(3);

        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], mIconSelectIds[i], mIconUnselectIds[i]));
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mApplication.unregisterReceiver(receiver);
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
        this.mTabEntities = null;
        this.mTitles = null;
        this.mIconUnselectIds = null;
        this.mIconSelectIds = null;
        this.mMainPagerAdapter = null;
    }

}
